package com.blog.upload;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.blog.util.FileUtil;

/** 
 * @author ant 
 * @date 创建时间：2017年8月21日 下午3:40:19  
 */
@RestController
public class UploadImage {
	
	@Value("${web.upload-path}")
	private String imagePath;
	
	@RequestMapping(value="/manage/uploadImage",method=RequestMethod.POST)
	public Map<String, Object> uploadImage(@RequestParam(value="image",required=false)MultipartFile file){
		String originalFilename = file.getOriginalFilename();
		String type = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		String fileName = FileUtil.getFileName() + type;
		File directory = new File(imagePath);
		if (!directory.exists()) {
			directory.mkdirs();
		}
		File localFile = new File(directory, fileName);
		Map<String, Object> map = new HashMap<>();
		try {
			file.transferTo(localFile);
			map.put("errno", 0);
			List<String> url = new LinkedList<>();
			url.add("/" + fileName);
			map.put("data", url);
		} catch (IllegalStateException | IOException e) {
			map.put("errno", 1);
			map.put("data", null);
			e.printStackTrace();
		}		
		return map;	
	}

}
